<template>
	<!-- 恒泰吴江版本 -->
	<view>
		<!-- 头部搜索框 -->
		<search :placeholder="$t('public.materialCode')" />
		<!-- 表格数据 -->
		<zy-table :headList="headList" :dataList="dataList" @editInput="editInput" :operationList="operationList"
			border>
		</zy-table>
		<!-- 底部按钮 -->
		<bottomBtn fixed :leftText="$t('public.reset')" :rightText="$t('homepage.WarehouseManage.select')"
			@rightBtn="selectBtn" @leftBtn="resetBtn" :leftDisabled="dataList.length>0?false:true"
			:rightDisabled="dataList.length>0?false:true">
		</bottomBtn>
		<!-- 选择按钮弹窗 -->
		<zy-popup ref="zyPopup" type='dialog' :title="$t('homepage.WarehouseManage.select')" @cancel="cancel"
			@confirm="submit" :closeOnClickOverlay="false">
			<zy-forms :model="model" :rules="rules" labelWidth="160">
				<zy-form-item :label="$t('homepage.WarehouseManage.type')" required>
					<picker mode="selector" @change="typeChange" :value="typeIndex" :range="typeColumn"
						:range-key="'label'">
						<view class="formItem" @click="typeBtn">
							<input class="formInput" v-model="model.type" disabled
								:placeholder="$t('public.pleaseSelect')+$t('homepage.WarehouseManage.type')" />
							<i class="iconfont icon-xiangxia1"></i>
						</view>
					</picker>
				</zy-form-item>
				<!-- <zy-form-item :label="$t('public.departMent')" required>
					<picker mode="multiSelector" @change="departChange" :value="departIndex" :range="departColumn">
						<view class="formItem" @click="departBtn">
							<input class="formInput" v-model="model.depart" disabled :placeholder="$t('public.pleaseSelect')+$t('public.departMent')" />
							<i class="iconfont icon-xiangxia1"></i>
						</view>
					</picker>
				</zy-form-item> -->
				<zy-form-item :label="$t('public.productionNo')" required>
					<zy-input v-model="model.productionNo"
						:placeholder="$t('public.pleaseInput')+$t('public.productionNo')" sufSlot>
						<i class="iconfont icon-saoyisao" @click="rightIconHandler"></i>
					</zy-input>
				</zy-form-item>
			</zy-forms>
		</zy-popup>
		<!-- 出库提交二次确认 -->
		<zy-popup ref="popup" :title="$t('homepage.WarehouseManage.outstorageSure')" type="dialog"
			:closeOnClickOverlay="false" @confirm="submitBtn">
			{{$t('public.isSure')}}{{model.type}}{{$t('public.question')}}
		</zy-popup>
	</view>
</template>
<script>
	import {
		getStorehouseDetailByCode,
		queryDictByType,
		queryTreeList,
		saveStorehouseOut
	} from "@/api/homepage.js"
	import search from "@/components/topSearch/index.vue";
	import bottomBtn from "@/components/bottomBtn/index.vue";
	export default {
		components: {
			search,
			bottomBtn
		},
		data() {
			return {
				//表格表头
				headList: [{
					name: this.$t('homepage.WarehouseManage.instorageCode'),
					key: 'barcode',
					width: 150
				}, {
					name: this.$t('public.surplusNum'),
					key: 'surplusNum',
					sum: true
				}, {
					name: this.$t('public.deliveryNum'),
					key: 'num',
					edit: true,
					type: 'number',
					sum: true
				}],
				dataList: [], //表格数据
				//表格操作列
				operationList: [{
					kind: "button",
					type: "warn",
					handle: this.delBtn,
					label: this.$t('public.del'),
				}],
				//弹窗表单数据
				model: {
					type: this.$t('homepage.WarehouseManage.pickOutStorage'),
					// depart: '',
					productionNo: ''
				},
				//form校验
				rules: {
					type: {
						required: true,
						message: this.$t('public.pleaseSelect') + this.$t('homepage.WarehouseManage.type'),
						trigger: ['blur', 'change']
					},
					depart: {
						required: true,
						message: this.$t('public.pleaseSelect') + this.$t('public.department'),
						trigger: ['blur', 'change']
					}
				},
				typeColumn: [], //类型下拉框数据
				typeIndex: 0,
				typeValue: 0,
				departColumn: [], //部门下拉框数据
				departIndex: [0, 0],
				departParent: [],
				departChild: [],
				departChilds: [],
				departId: '',
			}
		},
		onLoad() {
			this.getscancodedate()
		},
		onUnload() {
			// 移除监听事件      
			uni.$off('scancodedate')
			uni.$off('scancodepopdate')
		},
		methods: {
			//主页获取箱号扫描事件
			getscancodedate() {
				// 移除监听“添加扫描”弹窗事件
				uni.$off('scancodepopdate')
				//PDA扫描主页指示单号
				var _this = this
				uni.$on('scancodedate', function(data) {
					_this.searchList(data.code)
				})
			},
			//“弹窗生产单号”获取扫描事件
			getscancodepopdate() {
				// 移除监听“指示单号”事件
				uni.$off('scancodedate')
				//PDA扫描“添加扫描”弹窗事件
				var _this = this
				uni.$on('scancodepopdate', function(data) {
					_this.model.productionNo = data.code
				})
			},
			searchList(e) {
				console.log(e)
				getStorehouseDetailByCode({
					code: e,
					status: "2", //恒泰出库
				}).then((res) => {
					console.log(res)
					if (res.code == 0) {
						// if (res.data.status == 1) {
						if (this.dataList.length == 0) {
							this.dataList.push(res.data)
						} else {
							this.dataList.forEach((m, n) => {
								if (m.productionTask && res.data.productionTask !== m.productionTask) {
									uni.showToast({
										title: "生产单不匹配，请重新扫码",
										icon: "none",
										duration: 3000
									})
								} else {
									if (this.dataList.findIndex(item => item.barcode === e) !== -1) {
										uni.showToast({
											title: "重复查询",
											icon: "none",
											duration: 3000
										})
									} else {
										this.dataList.push(res.data)
									}
								}
							})
						}
						// } else {
						// 	uni.showToast({
						// 		title: "此编码" + res.data.statusText,
						// 		icon: "none",
						// 		duration: 3000
						// 	})
						// }
					} else {
						uni.showToast({
							title: res.message,
							icon: "none",
							duration: 3000
						})
					}
					this.dataList.forEach((item, index) => {
						this.dataList[index].num = this.dataList[index].surplusNum
					})
				}).catch((res) => {
					uni.showToast({
						title: res.message,
						icon: "none",
						duration: 3000
					})
				});
			},
			//编辑出库数量
			editInput(val) {
				if (Number(val.item.num) > Number(this.dataList[val.index].surplusNum)) {
					this.dataList[val.index].num = this.dataList[val.index].surplusNum
					uni.showToast({
						title: this.$t('public.max') + this.$t('public.colon') + this.dataList[val.index]
							.surplusNum,
						icon: "none",
						duration: 3000
					})
				}
			},
			// 删除数据事件
			delBtn(item, index) {
				console.log(item, index)

				this.dataList.splice(index, 1);
			},
			//重置按钮
			resetBtn() {
				uni.redirectTo({
					url: "/pages/HomePage/WarehouseManage/StorageManagement/Outstorage/index"
				})
			},
			// 底部选择按钮事件
			selectBtn() {
				this.$refs.zyPopup.open()
				this.getscancodepopdate()
			},
			//类型按钮
			typeBtn() {
				this.typeColumn = []
				queryDictByType({
					type: "storehouse_out_type"
				}).then((res) => {
					for (var i = 0; i < res.data.length; i++) {
						let obj = {}
						obj.value = res.data[i].value
						obj.label = res.data[i].label
						this.typeColumn.push(obj)
					}
				}).catch((res) => {
					uni.showToast({
						title: res.message,
						icon: "none",
						duration: 3000
					})
				});
			},
			//类型选择器完成事件
			typeChange(e) {
				this.typeColumn.forEach((item, index) => {
					if (e.detail.value == index) {
						this.typeValue = item.value
						this.model.type = item.label
						if (this.model.type == '销售出库' || this.model.type == '半成品出库' || this.model.type ==
							'待包装成品出库' || this.model.type == '待装箱成品出库' || this.model.type == '待发货成品出库') {
							this.model.productionNo = this.dataList[0].productionTask
						} else {
							this.model.productionNo = ''
						}
					}
				})
			},
			//部门按钮
			departBtn() {
				this.departColumn = []
				this.departParent = []
				this.departChild = []
				this.departChilds = []
				queryTreeList().then((res) => {
					//选择器中父列数据
					this.departParent = res.data.map((item) => item.title)
					//选择器中子列数据
					for (var i = 0; i < res.data.length; i++) {
						for (var j = 0; j < res.data[i].children.length; j++) {
							let obj = {}
							obj.label = res.data[i].children[j].title,
								obj.id = res.data[i].children[j].id
							this.departChild.push(res.data[i].children[j].title)
							this.departChilds.push(obj)
						}
					}
					this.departColumn.push(this.departParent, this.departChild)
				}).catch((res) => {
					uni.showToast({
						title: res.message,
						icon: "none",
						duration: 3000
					})
				});
			},
			//部门弹框确认
			departChange(e) {
				this.departChilds.forEach((item, index) => {
					if (e.detail.value[1] == index) {
						this.departId = item.id
						this.model.depart = item.label
					}
				})
			},
			// 生产单号弹窗扫描
			rightIconHandler() {
				var mpaasScanModule = uni.requireNativePlugin("Mpaas-Scan-Module")
				mpaasScanModule.mpaasScan({
						// 扫码识别类型，参数可多选，qrCode、barCode，不设置，默认识别所有
						'scanType': ['qrCode', 'barCode'],
						// 是否隐藏相册，默认false不隐藏
						'hideAlbum': false
					},
					(ret) => {
						if (ret.resp_result) {
							this.model.productionNo = ret.resp_result.replace(/\s/g, "");
						}
					})
			},
			//出库二次确认按钮事件
			submit() {
				if (!this.model.type || !this.model.productionNo) {
					uni.showToast({
						title: this.$t('homepage.WarehouseManage.formUnNull'),
						icon: "none",
						duration: 3000
					})
				} else {
					this.$refs.popup.open()
				}
			},
			// 弹窗取消事件
			cancel() {
				let that = this
				that.getscancodedate()
			},
			//确认出库
			submitBtn() {
				saveStorehouseOut({
					billType: this.typeValue, //单据类型 
					// applyDeptId: this.departId, //领料部门id
					// applyDept: this.model.depart,
					productionNo: this.model.productionNo,
					orderId: "", //订单id （成品出库选订单）
					dataArray: JSON.stringify(this.dataList), //库存数组 （扫码获取的数据，多个逗号隔开）
				}).then((res) => {
					if (res.code == 0) {
						uni.showToast({
							title: res.message,
							icon: "none",
							duration: 3000
						})
						this.resetBtn()
					} else {
						uni.showToast({
							title: res.message,
							icon: "none",
							duration: 3000
						})
					}
				}).catch((res) => {
					uni.showToast({
						title: res.message,
						icon: "none",
						duration: 3000
					})
				});
			},
		}
	}
</script>
<style lang="scss" scoped>
	.formItem {
		width: calc(100% - 40rpx);
		padding: 20rpx;
		display: flex;
		border: 1px solid #e9e9e9;
		border-radius: 10rpx;
		background-color: #f5f5f5;
	}

	.formInput {
		margin: auto 0;
		width: 100%;
		border: none;
		outline: none;
		font-size: 32rpx;
		z-index: 999999;
	}

	.iconfont {
		margin: auto 0 auto 10rpx;
		font-size: 28rpx;
		color: #999999;
	}
</style>